package com.touzhijia.authority.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.touzhijia.authority.domain.dto.request.*;
import com.touzhijia.authority.domain.dto.response.UserModuleAddRes;
import com.touzhijia.authority.domain.dto.response.UserRoleAddRes;
import com.touzhijia.authority.domain.entity.Role;
import com.touzhijia.authority.domain.entity.User;
import com.touzhijia.authority.exception.BusinessException;
import com.touzhijia.authority.mapper.RoleMapper;
import com.touzhijia.authority.mapper.UserMapper;
import com.touzhijia.authority.utils.mapper.BeanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 作者： lzw<br/>
 * 创建时间：2018-03-14 14:28 <br/>
 */
@Transactional(readOnly = true)
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    public User getUser(String username) {
        return userMapper.getByUsername(username);
    }

    public PageInfo<User> findUser(UserQueryReq queryRes) {
        return PageHelper
                .startPage(queryRes.getPageNo(), queryRes.getPageSize())
                .doSelectPageInfo(() -> userMapper.findUser(queryRes));
    }

    @Transactional
    public User addUser(UserAddReq userAddReq) {
        User exists = userMapper.getByUsername(userAddReq.getUsername());
        if (exists != null) {
            throw new BusinessException("用户已经存在");
        }
        User user = BeanMapper.mapper(userAddReq, User.class);
        user.setUserType(User.User_Type_0);
        user.setLdapExist(User.Ldap_Exist_0);
        user.setLocked(User.Locked_0);
        user.setEnabled(User.Enabled_1);
        user.setCreateAt(new Date());
        userMapper.insertSelective(user);
        return user;
    }

    @Transactional
    public User delUser(String username) {
        User user = userMapper.getByUsername(username);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        if (Objects.equals(user.getUserType(), User.User_Type_1)) {
            throw new BusinessException("当前用户不能删除");
        }
        // 删除 user
        userMapper.deleteByUsername(username);
        // 删除 user_role
        userMapper.delUserRoleByUsername(username);
        // 删除 user_module
        userMapper.delUserModuleByUsername(username);
        // TODO Spring Security 处理
        return user;
    }

    @Transactional
    public User updateUser(String username, UserUpdateReq userUpdateReq) {
        User user = userMapper.getByUsername(username);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        User update = BeanMapper.mapper(userUpdateReq, User.class);
        update.setId(user.getId());
        update.setUpdateAt(new Date());
        userMapper.updateByPrimaryKeySelective(update);
        return userMapper.getByUsername(username);
    }

    @Transactional
    public UserRoleAddRes addUserRole(UserRoleAddReq addReq) {
        User user = userMapper.getByUsername(addReq.getUsername());
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        Role role = roleMapper.getByName(addReq.getRoleName());
        if (role == null) {
            throw new BusinessException("角色不存在");
        }
        int count = userMapper.existsRole(addReq.getUsername(), addReq.getRoleName());
        if (count != 0) {
            throw new BusinessException("当前用户已拥有该角色");
        }
        userMapper.addRole(addReq.getUsername(), addReq.getRoleName());
        return new UserRoleAddRes(user.getUsername(), role.getName());
    }

    @Transactional
    public UserRoleAddRes removeUserRole(String username, String roleName) {
        User user = userMapper.getByUsername(username);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        Role role = roleMapper.getByName(roleName);
        if (role == null) {
            throw new BusinessException("角色不存在");
        }
        int count = userMapper.existsRole(username, roleName);
        if (count != 1) {
            throw new BusinessException("操作无效，当前用户未拥有该角色");
        }
        userMapper.delRole(username, roleName);
        return new UserRoleAddRes(user.getUsername(), role.getName());
    }

    @Transactional
    public UserModuleAddRes addUserModule(UserModuleAddReq addReq) {
        User user = userMapper.getByUsername(addReq.getUsername());
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        int count = userMapper.existsModule(addReq.getUsername(), addReq.getModule());
        if (count != 0) {
            throw new BusinessException(String.format("用户[%1$s]已经有权登录[%2$s]", addReq.getUsername(), addReq.getModule()));
        }
        userMapper.addModule(addReq.getUsername(), addReq.getModule());
        return new UserModuleAddRes(addReq.getUsername(), addReq.getModule());
    }

    @Transactional
    public UserModuleAddRes delUserModule(String username, String module) {
        User user = userMapper.getByUsername(username);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        int count = userMapper.existsModule(username, module);
        if (count != 1) {
            throw new BusinessException(String.format("操作无效，用户[%1$s]当前无权登录[%2$s]", username, module));
        }
        userMapper.delModule(username, module);
        return new UserModuleAddRes(username, module);
    }

    public List<String> findModuleByUser(String username) {
        return userMapper.findModuleByUser(username);
    }
}
